package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.exception.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.pojo.vo.PictureStandardVO;
import cn.tedu.csmall.product.service.PictureService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 处理图片业务的实现类
 *
 * @author Chen
 * @since 2023/2/11 8:50:50
 */
@Slf4j
@Service
public class PictureServiceImpl implements PictureService {

    private final PictureMapper pictureMapper;
    private final AlbumMapper albumMapper;

    @Autowired
    public PictureServiceImpl(PictureMapper pictureMapper, AlbumMapper albumMapper) {
        log.debug("创建业务实现类对象：PictureServiceImpl");
        this.pictureMapper = pictureMapper;
        this.albumMapper = albumMapper;
    }

    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("开始处理【添加图片】的业务，参数：{}", pictureAddNewDTO);
        // 查询是否存在该相册
        Long albumId = pictureAddNewDTO.getAlbumId();
        AlbumStandardVO albumStandardVO = albumMapper.getStandardById(albumId);
        if (albumStandardVO == null) {
            String message = "添加图片失败，尝试访问的相册不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureAddNewDTO, picture);
        log.debug("即将执行【添加图片】的业务，参数：{}", picture);
        int rows = pictureMapper.insert(picture);
        if (rows != 1) {
            String message = "添加图片失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【删除图片】的业务，参数：{}", id);
        // 根据id查询是否存在此图片
        PictureStandardVO pictureStandardVO = pictureMapper.getStandardById(id);
        if (pictureStandardVO == null) {
            String message = "删除图片失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将执行删除，参数：{}", id);
        int rows = pictureMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除图片失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

}
